package com.leyou.search.service.impl;

import com.leyou.common.dto.PageDTO;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.search.constants.IndexConstants;
import com.leyou.search.dto.SearchParamDTO;
import com.leyou.search.entity.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.SearchService;
import com.leyou.starter.elastic.dto.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Mono;

import java.util.*;
import java.util.stream.Collectors;

import static com.leyou.search.constants.IndexConstants.INDEX_SOURCE;
import static com.leyou.search.constants.IndexConstants.SUGGESTION_FIELD;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class SearchServiceImpl implements SearchService {

    private final GoodsRepository repository;
    private final ItemClient itemClient;

    public SearchServiceImpl(GoodsRepository repository, ItemClient itemClient) {
        this.repository = repository;
        this.itemClient = itemClient;
    }

    @Override
    public void createIndexAndMapping() {
        // 删除索引库
        try {
            repository.deleteIndex();
        } catch (Exception e) {
            log.warn("索引库可能不存在或者已经删除，无需再次删除。", e);
        }
        // 创建索引库及映射
        repository.createIndex(INDEX_SOURCE);
    }

    @Override
    public void loadData() {
        int page = 1, rows = 50;
        log.info("准备开始导入数据。");
        while (true) {
            log.debug("开始导入第{}页数据，共{}条。", page, rows);
            // 查询商品Spu相关信息
            PageDTO<SpuDTO> result = itemClient.querySpuByPage(page, rows, true, null, null, null);
            List<SpuDTO> list = result.getItems();
            // 创建一个goods集合，用来封装goods数据
            List<Goods> goodsList = new ArrayList<>(list.size());

            for (SpuDTO spuDTO : list) {
                // 把信息封装到Goods对象
                Goods goods = buildGoods(spuDTO);
                goodsList.add(goods);
            }
            // 把Goods对象写入索引库
            repository.saveAll(goodsList);
            log.debug("导入第{}页数据成功，实际导入共{}条。", page, goodsList.size());
            // 翻页
            page++;
            // 判断是否是最后一页
            if (page > result.getTotalPage()) {
                // 最后一页了
                break;
            }
        }
        log.debug("数据导入完成！");
    }

    @Override
    public Mono<List<String>> getSuggestion(String keyPrefix) {
        if (StringUtils.isBlank(keyPrefix)) {
            throw new LyException(400, "请求参数不能为空！");
        }
        return repository.suggestBySingleField(SUGGESTION_FIELD, keyPrefix);
    }

    @Override
    public Mono<PageInfo<Goods>> search(SearchParamDTO paramDTO) {
        // 健壮性判断
        String key = paramDTO.getKey();
        if (StringUtils.isBlank(key)) {
            return Mono.error(new LyException(400, "请求参数不能为空!"));
        }
        // 搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 1.source过滤
        sourceBuilder.fetchSource(IndexConstants.DEFAULT_SOURCE_FIELD, null);

        // 2.关键字搜索和过滤
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        // 关键字搜索
        queryBuilder.must(QueryBuilders.matchQuery(IndexConstants.DEFAULT_SEARCH_FIELD, key));
        // 以后添加关键字过滤条件
        // queryBuilder.filter(null);
        sourceBuilder.query(queryBuilder);

        // 3.分页
        sourceBuilder.from(paramDTO.getFrom()).size(paramDTO.getSize());

        // 4.排序
        String sortBy = paramDTO.getSortBy();
        if(StringUtils.isNotBlank(sortBy)) {
            sourceBuilder.sort(sortBy, paramDTO.getDesc() ? SortOrder.DESC : SortOrder.ASC);
        }

        // 5.高亮
        sourceBuilder.highlighter(
                new HighlightBuilder().field(IndexConstants.DEFAULT_SEARCH_FIELD).preTags("<am>").postTags("</am>"));

        return repository.queryBySourceBuilderForPageHighlight(sourceBuilder);
    }

    @Override
    public void saveGoods(Long spuId) {
        // 查询spu
        SpuDTO spu = itemClient.queryGoodsById(spuId);
        // 封装goods
        Goods goods = buildGoods(spu);
        // 新增goods
        repository.save(goods);
    }

    @Override
    public void deleteGoods(Long spuId) {
        boolean boo = repository.deleteById(spuId);
        if (!boo) {
            throw new RuntimeException("删除失败！");
        }
    }

    private Goods buildGoods(SpuDTO spu) {
        // 1.商品标题，搜索字段包含：商品标题、分类名称、品牌名称
        // 1.1.分类名称
        String categoryName = spu.getCategoryName();
        // 1.2.品牌名称
        String brandName = spu.getBrandName();
        String title = spu.getTitle() + categoryName + brandName;

        // 2.suggestion 自动补全字段，包含分类、品牌、商品名称
        List<String> suggestion = new ArrayList<>();
        suggestion.add(brandName);
        suggestion.add(spu.getName());
        Collections.addAll(suggestion, categoryName.split("/"));

        // 3.销量、价格、图片
        // 3.1.查询sku
        List<SkuDTO> skuList = spu.getSkus();
        if (CollectionUtils.isEmpty(skuList)) {
            // 查询
            skuList = itemClient.querySkuBySpuId(spu.getId());
        }
        // 3.2.销量，各个sku销量的和
        long sold = skuList.stream().mapToLong(SkuDTO::getSold).sum();
        // 3.3.价格，各个sku的价格的集合
        Set<Long> prices = skuList.stream().map(SkuDTO::getPrice).collect(Collectors.toSet());
        // 3.4.图片，任意取出一个sku的第一张图片
        String image = StringUtils.substringBefore(skuList.get(0).getImages(), ",");

        // 4.规格参数
        // 4.1.查询规格参数键值对
        List<SpecParamDTO> params = itemClient.querySpecsValues(spu.getId(), true);
        // 4.2.把params存入map
        List<Map<String, Object>> specs = new ArrayList<>(params.size());
        for (SpecParamDTO param : params) {
            // 准备map，保存name和value
            Map<String, Object> map = new HashMap<>(2);
            map.put("name", param.getName());
            map.put("value", chooseSegment(param));
            specs.add(map);
        }

        // 5.创建goods对象
        Goods goods = new Goods();
        goods.setUpdateTime(new Date());
        goods.setTitle(title);
        goods.setSuggestion(suggestion);
        goods.setSpecs(specs);
        goods.setSold(sold);
        goods.setPrices(prices);
        goods.setImage(image);
        goods.setId(spu.getId());
        goods.setCategoryId(spu.getCid3());
        goods.setBrandId(spu.getBrandId());
        return goods;
    }

    private Object chooseSegment(SpecParamDTO p) {
        Object value = p.getValue();
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        if (!p.getNumeric() || StringUtils.isBlank(p.getSegments()) || value instanceof Collection) {
            return value;
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }
}
